package cn.hlyc.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class TimeFilter implements GatewayFilter, Ordered {

    private static final String START_TIME_KEY = "startTime";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //记录开始时间
        Long startTime = System.currentTimeMillis();
        //将参数放到exchange的Attribute里面
        exchange.getAttributes().put(START_TIME_KEY,startTime);
        //结束后要执行的代码
        return chain.filter(exchange).then(
            Mono.fromRunnable(()->{
                Long endTime = System.currentTimeMillis();
                //到exchange中拿到刚才记录的那个开始时间
                Long time =(Long)exchange.getAttributes().get(START_TIME_KEY);
                //获取当前请求的路径
                String url = exchange.getRequest().getURI().getPath();
                System.out.println("请求路径为:" + url + "请求时长为:" + (endTime - time));
           })
        );
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
